package com.jin.blog.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.jin.blog.core.BlogConstants;
import com.jin.blog.pojo.Article;

public class ArticleController extends BaseController {
	public void index() {
		final Integer articleId = getParaToInt(0);
		Article article = CacheKit.get("article", "id_" + articleId, new IDataLoader() {
			@Override
			public Object load() {
			    return Article.dao.findById(articleId);
			}
		});
		Article.dao.clear().set("id", articleId).set("viewCount", article.getInt("viewCount") + 1).update();
		setAttr("artDetail", article);
		
		Article previous = CacheKit.get("article", "id_p_" + articleId, new IDataLoader() {
			@Override
			public Object load() {
			    return Article.dao.findFirst("select id,title from article where id < ?  order by id desc limit 0,1", articleId);
			}
		});
		if(previous != null){
			setAttr("previous", previous);
		}
		
		Article next = CacheKit.get("article", "id_n_" + articleId, new IDataLoader() {
			@Override
			public Object load() {
			    return Article.dao.findFirst("select id,title from article where id > ?  order by id asc limit 0,1", articleId);
			}
		});
		if(next != null){
			setAttr("next", next);
		}
		
		List<Map<String, Object>>crumbs = new ArrayList<>();
		Map<String, Object>m1 = new HashMap<>();
		m1.put("url", "project/" + article.getInt("projectId"));
		m1.put("name", article.get_project().getStr("name"));
		crumbs.add(m1);
		Map<String, Object>m2 = new HashMap<>();
		m2.put("name", article.getStr("title"));
		crumbs.add(m2);
		setAttr("crumbs", crumbs);
		
		getCommonData();
		
		render("detail.html");
	}
	public void hotsView(){
		final Integer pageNum = getParaToInt("p") == null ? 1 : getParaToInt("p");
		Page<Article> page = Article.dao.paginateByCache("article", "hotsView_" + pageNum, pageNum, BlogConstants.PAGE_SIZE, 
				"select * ", 
				"from article where finish = 1 order by viewCount desc");
		setAttr("page", page);
		render("articles.html");
	}
	public void hotsReply(){
		final Integer pageNum = getParaToInt("p") == null ? 1 : getParaToInt("p");
		Page<Article> page = Article.dao.paginateByCache("article", "hotsReply_" + pageNum, pageNum, BlogConstants.PAGE_SIZE, 
				"select * ", 
				"from article where finish = 1 order by replyCount desc"); 
		setAttr("page", page);
		render("articles.html");
	}

}
